import * as React from 'react';
import { enableScreens } from 'react-native-screens';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { Provider, useDispatch, useSelector } from 'react-redux'; // 引入 Redux Provider
import { store } from './src/Store/store'; // 引入 Redux Store
import ProfileScreen from './src/Pages/ProfileScreen';
import WaterFallListScreen from './src/Pages/WaterFallListScreen.tsx';
import SearchScreen from './src/Pages/SearchScreen.tsx';
import { Linking, SafeAreaView, StatusBar, Text, TouchableOpacity, useColorScheme } from 'react-native';
import PublishScreen from './src/Pages/PublishScreen.tsx';
import NoteDetailScreen from './src/Pages/NoteDetailScreen.tsx';
import RBSheet from 'react-native-raw-bottom-sheet';
import LoginForm from './src/Pages/LoginFormScreen.tsx';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { setLogin } from './src/Store/actions.ts';
import { RootState } from './src/Store/store';
import MyNoteScreen from './src/Pages/MyNoteScreen.tsx'; // 引入 RootState 类型
import Icon from 'react-native-vector-icons/FontAwesome';
enableScreens();

// 创建应用程序的导航容器
const Stack = createStackNavigator();

// 创建底部标签页导航器
const Tab = createBottomTabNavigator();

// 定义 TabNavigator
// @ts-ignore
const TabNavigator = ({navigation}) => {
  const refRBSheet = React.useRef<any>(null);
  const isLogin = useSelector((state: RootState) => state.loginState.isLogin); // 使用 RootState 类型
  const tabNavigation = useNavigation();
  const colorScheme = useColorScheme();
  const isDarkMode = colorScheme === 'dark';
  const dispatch = useDispatch();
  React.useEffect(() => {
    const restoreLoginState = async () => {
      const storedLoginState = await AsyncStorage.getItem('loginState');
      if (storedLoginState) {
        const { isLogin, userInfo } = JSON.parse(storedLoginState);
        // @ts-ignore
        dispatch(setLogin(isLogin, userInfo)); // 恢复 Redux 状态
      }
    };
    restoreLoginState();
  }, [dispatch]);
  const handlePublishPress = () => {
    if (!isLogin) {
      refRBSheet.current?.open();
    } else {
      // @ts-ignore
      tabNavigation.navigate('TabNavigator', { screen: 'Publish' });
    }
  };

  const handleProfilePress = () => {
    if (!isLogin) {
      refRBSheet.current?.open();
    } else {
      // @ts-ignore
      tabNavigation.navigate('TabNavigator', { screen: 'Profile' });
    }
  };
  const handleDeeplink = (urlObj: any) => {
    // 处理 Deeplink 的逻辑
    // 例如，导航到特定的屏幕
    const url:string = urlObj._url;
    // url格式为 ctn://note/id/1231
    if(!url.startsWith('ctn://')) {
      return;
    }
    const slicedUrl:string = url.slice(6);
    const urlParts = slicedUrl.split('/');
    if (urlParts.length > 1) {
      if(urlParts[0]=='note'&&urlParts[1]=='id'){
        navigation.navigate('NoteDetailScreen', { id: urlParts[2] });
      }
    }
  };

  useDeeplinkHandler(handleDeeplink);

  // @ts-ignore
  return (
    <>
      <Tab.Navigator
        screenOptions={() => {

          return {
            headerShown: false,
            tabBarItemStyle: {
              paddingVertical: 5,
              justifyContent: 'center',
            },
            tabBarIconStyle: {
              display: 'none',
            },
            tabBarLabelStyle: {
              fontWeight: 'bold',
              fontSize: 22,
              color: isDarkMode ? '#FFFFFF' : '#000000',
            },
            tabBarStyle: {
              backgroundColor: isDarkMode ? '#121212' : '#fff',
              justifyContent: 'center', // 让底部导航栏内容居中
              alignItems: 'center',
              flexDirection: 'row',
              paddingHorizontal: 20 // 适当添加水平内边距
            }
          };
        }}>
        <Tab.Screen
          name="Home"
          component={WaterFallListScreen}
          options={{
            tabBarLabel: '首页',
          }}
        />
        <Tab.Screen
          name="Publish"
          component={PublishScreen}
          options={{
            tabBarButton: props => (
              <TouchableOpacity
                {...props}
                onPress={handlePublishPress}
                style={{
                  backgroundColor: '#007AFF', // 浅蓝色背景
                  borderRadius: 10,
                  width: 80,
                  height: 50,
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginHorizontal: 20 // 添加水平外边距，让按钮有间隔
                }}
              >
                <Icon name="plus" size={22} color="#fff" />
              </TouchableOpacity>
            ),
          }}
        />
        <Tab.Screen
          name="Profile"
          component={ProfileScreen}
          options={{
            tabBarLabel: '我的',
            tabBarButton: props => (
              <TouchableOpacity
                {...props}
                onPress={handleProfilePress}
              >
                <Text style={{ fontWeight: 'bold', fontSize: 22, color: isDarkMode ? '#FFFFFF' : '#000000' }}>我的</Text>
              </TouchableOpacity>
            ),
          }}
        />
      </Tab.Navigator>

      {/*RBSheet组件*/}
      <RBSheet
        ref={refRBSheet}
        height={300}
        customStyles={{
          wrapper: {
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
          },
          draggableIcon: {
            backgroundColor: '#000',
          },
          container: {
            borderTopLeftRadius: 20,
            borderTopRightRadius: 20,
          },
        }}>
        <LoginForm/>
      </RBSheet>
    </>
  );
};

// 自定义 Hook 用于处理 Deeplink
const useDeeplinkHandler = (onDeeplinkReceived: any) => {
  React.useEffect(() => {
    const getInitialUrl = async () => {
      const initialUrl = await Linking.getInitialURL();
      if (initialUrl) {
        try {
          const urlObj = new URL(initialUrl);
          onDeeplinkReceived(urlObj);
        } catch (error) {
          console.error('Error parsing initial URL:', error);
        }
      }
    };

    getInitialUrl();

    const subscription = Linking.addEventListener('url', ({ url }) => {
      try {
        const urlObj = new URL(url);
        onDeeplinkReceived(urlObj);
      } catch (error) {
        console.error('Error parsing incoming URL:', error);
      }
    });

    return () => subscription.remove();
  }, [onDeeplinkReceived]);
};

// 定义 StackNavigator 并将 TabNavigator 嵌套其中
const App = () => {
  const colorScheme = useColorScheme();
  const isDarkMode = colorScheme === 'dark';


  return (
    <>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} backgroundColor={isDarkMode ? '#121212' : '#fff'} />
      <SafeAreaView style={{ flex: 1, backgroundColor: isDarkMode ? '#121212' : '#fff' }}>
        {/* 使用 Redux Provider 包裹整个应用 */}
        <Provider store={store}>
          <NavigationContainer>
            <Stack.Navigator
              initialRouteName="TabNavigator"
              screenOptions={{ headerShown: false }}>
              <Stack.Screen name="TabNavigator" component={TabNavigator} />
              <Stack.Screen name="SearchScreen" component={SearchScreen} />
              <Stack.Screen
                name="NoteDetailScreen"
                component={NoteDetailScreen}
              />
              <Stack.Screen name="MyNoteScreen" component={MyNoteScreen} />
            </Stack.Navigator>
          </NavigationContainer>
        </Provider>
      </SafeAreaView>
    </>
  );
};

export default App;
